from django.http import HttpResponse
import pandas as pd
from rest_framework.viewsets import GenericViewSet
import chardet

from celery_task.task import create_report
from utils.common_mixin import APIListModelMixin, APICreateModelMixin, APIUpdateModelMixin
from utils.common_response import APIResponse
from .models import Book
from .serializer import BookSerializer


class BookListView(GenericViewSet, APIListModelMixin):
    queryset = Book.objects.all()
    serializer_class = BookSerializer


class BookUpdateView(GenericViewSet, APIUpdateModelMixin):
    queryset = Book.objects.all()
    serializer_class = BookSerializer


def detect_encoding(file):
    rawdata = file.read(1024)
    result = chardet.detect(rawdata)
    encoding = result['encoding']
    confidence = result['confidence']
    return encoding, confidence


class BookImportView(GenericViewSet, APICreateModelMixin):
    def create(self, request, *args, **kwargs):
        # ··print(request.data)
        file = request.FILES.get('file')
        if file:
            # 检测文件编码
            encoding, confidence = detect_encoding(file)
            print('encoding', encoding)
            file.seek(0)  # 重置文件指针，否则后续读取会失败
            print('--file:', file.name)
            # print('type',type(file))
            # 使用检测到的编码读取 CSV 文件
            if file.name.endswith('.csv'):
                df = pd.read_csv(file, encoding=encoding)
                # 提取列名
                column_names = df.columns.tolist()[0]

                title, author, publication_date = column_names.split(' ')
                print(title)
                print(author)
                print(publication_date)
                Book.objects.create(title=title, author=author, publication_date=publication_date)
                return APIResponse(msg='上传成功')
            if file.name.endswith('.xls'):
                df = pd.read_csv(file, encoding=encoding)
                # 提取列名
                column_names = df.columns.tolist()[0]
                title, author, publication_date = column_names.split(' ')
                print(title)
                print(author)
                print(publication_date)
                Book.objects.create(title=title, author=author, publication_date=publication_date)
                return APIResponse(msg='上传成功')
        return APIResponse(msg='上传')


def test(request):
    from datetime import datetime, timedelta
    ctime = datetime.now()
    utc_time = datetime.utcfromtimestamp(ctime.timestamp())
    time_delay = timedelta(seconds=10)
    task_time = utc_time + time_delay
    result = create_report.apply_async(eta=task_time)
    return HttpResponse('ok')
